package com.crysta1.picviewer;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;  // 关键导入

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PERMISSIONS = 1001;
    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    private RecyclerView recyclerView;
    private ImageAdapter adapter;
    static List<ImageItem>  imageList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 初始化视图
        setupViews();

        // 检查并请求权限
        if (checkAllPermissionsGranted()) {
            initializeApp();
        } else {
            requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
        }
    }

    private void setupViews() {
        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ImageAdapter(imageList);
        recyclerView.setAdapter(adapter);

        // 设置按钮点击监听
        findViewById(R.id.btn_settings).setOnClickListener(v ->
                Toast.makeText(this, "功能未完成", Toast.LENGTH_SHORT).show());

        findViewById(R.id.btn_add).setOnClickListener(v -> showAddDialog());
    }

    private void initializeApp() {
        // 此处可以添加需要权限的初始化操作
        Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
    }

    private boolean checkAllPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (checkAllPermissionsGranted()) {
                initializeApp();
            } else {
                handlePermissionsDenied();
            }
        }
    }

    private void handlePermissionsDenied() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // 用户拒绝但未勾选"不再询问"
            new AlertDialog.Builder(this)
                    .setTitle("需要存储权限")
                    .setMessage("此功能需要存储权限来保存图片到相册")
                    .setPositiveButton("重试", (d, w) ->
                            requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS))
                    .setNegativeButton("取消", null)
                    .show();
        } else {
            // 用户勾选"不再询问"
            Toast.makeText(this, "请在设置中授予权限", Toast.LENGTH_LONG).show();
            openAppSettings();
        }
    }

    private void openAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }


    private void showAddDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_add_image, null); // 使用正确的布局
        EditText etUrl = view.findViewById(R.id.et_url);  // 修正ID
        EditText etTitle = view.findViewById(R.id.et_title); // 修正ID

        builder.setView(view)
                .setPositiveButton("确定", (dialog, which) -> { // 补全Lambda参数
                    String url = etUrl.getText().toString();
                    String title = etTitle.getText().toString();
                    // 在点击确定时添加验证
                    if (url.isEmpty() || !url.startsWith("http")) {
                        Toast.makeText(this, "请输入有效的URL地址", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        imageList.add(new ImageItem(title, url));
                        recyclerView.getAdapter().notifyDataSetChanged();
                    }
                })
                .setNegativeButton("取消", null) // 修正方法链格式
                .show(); // 确保链式调用正确结束
    }
}